// 权限树
var permissionTree = null;
// 组织树
var orgTree = null;
$(function(){
	// 加载表格
	searchTable = $("#searchTable").DataTable(dataTableConfig);
	//searchTable.ajax.reload();
});
////////// 	权限数展示       ///////////////////////
// 权限树设置
var permissionSetting = {
	check: {
		enable: true,
		chkboxType: {
			"Y":'ps', "N":'ps'
		},
	},
	view: {
		selectedMulti: true
	},
	data: {
		simpleData: {
			enable: true
		}
	},
	callback: {
		beforeClick: function(treeId, treeNode) {
			
		}
	}
};
// 组织树设置
var orgSetting = {
	view: {
		selectedMulti: false
	},
	data: {
		simpleData: {
			enable: true
		}
	},
	callback: {
		beforeClick: function(treeId, treeNode) {
			$('#orgIdObj').val(treeNode.id);
			$('#orgNameObj').val(treeNode.name);
			$('#orgIdObj').change();
			$('#orgCloseModal').click();
		}
	}
};
/////////////////  table 列表  ///////////////////////////////////////////
// 后面构建btn 代码
var btnModel = '    \
	{{#each func}}\
    <button type="button" class="btn btn-{{this.type}} btn-sm" onclick="{{this.fn}}">{{this.name}}</button>\
    {{/each}}';
var template = Handlebars.compile(btnModel);
var searchTable;
var contentBtn;
function btnFun(c){
	contentBtn = "";
	if(contentBtn){
		return contentBtn;
	}else{
		var btnArray = new Array();
		if(hadPermission.update){
			btnArray.push({"name": "修改", "fn": "showEditPage(\'" + c.id + "\')", "type": "primary"});
		}
		if(hadPermission.del){
			btnArray.push({"name": "删除", "fn": "del(\'" + c.id + "\',\'" + c.name + "\')", "type": "danger"});
		}
		if(hadPermission.search){
			btnArray.push({"name": "角色查看人员", "fn": "roleSearchStaff(\'" + c.id + "\')", "type": "primary"});
		}
		contentBtn = {
			func:btnArray
		}
		return contentBtn;
	}
	
}

// 表格配置信息
var dataTableConfig = {
	"ordering": false,// 排序
	"serverSide": true,// 开启服务器模式
	"scrollX": true,// 横向滚动
	ajax: {
        "type": "POST",
        "url":'search4Page.action',//请求路径
        "contentType": 'application/x-www-form-urlencoded; charset=UTF-8',
        "dataType":'json',
        "data":function(d){// 查询参数
        	d.name = $('#sysRoleName').val();
        	return d;
        }
	},            
	columns: [// 对应列
        {"data": "name"},
        {"data": "deptName"},
        {"data": null}
    ],
    "columnDefs": [
		{// 所有列默认值
			"targets": "_all",
			"defaultContent": ''
		},
       {// 最后一列添加按钮
        targets: -1,
        render: function (a, b, c, d) {
        	
//            var context =
//            {
//                func:btnArray 
//            };
        	var context = btnFun(c);
            var html = template(context);
            return html;
        }
    }],
    lengthMenu: [
			        [ 10, 25, 50 ],
			        [ '10', '25', '50']
			    ],
    "dom": 'lrt<"bottom"ip><"clear">' //生成样式
};

// 初始化页面信息
function initFrame(){
	$('#searchContent').show();
	$('#roleModal').hide();
//	$('#searchContent').hide();
	$('#addBtn').hide();
	$('#updateBtn').hide();
	$('#roleForm input').val('');
	$('#permissionNameUl').empty();
	resetValidator();
}
function resetValidator(){
	if($('#roleForm').data('bootstrapValidator')){
		$('#roleForm').data('bootstrapValidator').resetForm(false);
	}
}
// 查询
function serarch(){
	searchTable.ajax.reload();
}
// 加载权限组织信息
function loadData(fun,id){
	$.post('loadAssistData.action',{},function(data){
		permissionTree = $.fn.zTree.init($("#permissionTree"), permissionSetting, data.sysPermissions);
		permissionTree.expandAll(true);
		orgTree = $.fn.zTree.init($("#orgTree"), orgSetting, data.sysOrgs);
		orgTree.expandAll(true);
		/*if(fun){
			fun(id);
		}*/
	});
}

// 显示添加角色
function addRoleShow(){

//	$('#searchContent').hide();
	$('#updateBtn').hide();
	$('#roleForm input').val('');
	$('#permissionNameUl').empty();
	$('.upfpanel-title').text("角色新增");
	if(null == permissionTree){ 
		loadData(addRoleShow);
	}
	$('#addBtn').show();
//	$('#showRole').click();
	$('#searchContent').hide();
	$('#roleModal').show();
	$("#controlLevelRoleObj").val('-1');
	if(null == $('#roleForm').data('bootstrapValidator')) {
		$('#roleForm').bootstrapValidator(checkValidator);
	}
	resetValidator();
    $('#orgIdObj').on('change', function(e) {
        $('#roleForm')
            .data('bootstrapValidator')
            .updateStatus('orgId', 'NOT_VALIDATED', null)
            .validateField('orgId');
    });
	
}

var checkValidator = {
		message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            name: {
                validators: {
                    notEmpty: {
                        message: '请输入角色名称'
                    }
                }
            },
            orgId: {
            	selector:'#orgNameObj',
            	
                validators: {
                    notEmpty: {
                        message: '请单击选择所属部门'
                    }
                }
            }
        },
        submitHandler: function(validator, form, submitButton) {
            // Use Ajax to submit form data
			if($(submitButton).attr('id') == 'addBtn'){
				addRole();
			}
        	if($(submitButton).attr('id') == 'updateBtn'){
				updateRole();
			}
        	
        	
        }

};

var checkValidator1 = {
		message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            name: {
                validators: {
                    notEmpty: {
                        message: '请输入角色名称'
                    }
                }
            }
           
        },
        submitHandler: function(validator, form, submitButton) {
            // Use Ajax to submit form data
        	updateRole();
        	
        	
        }

};

// 添加角色至后台
function addRole(){
	var treeObj = $.fn.zTree.getZTreeObj("permissionTree");
	var nodes = treeObj.getCheckedNodes(true);
	var str = '';
	for(var i = 0 ; i < nodes.length; i++){
		str += nodes[i].id;
		str += ",";	
	}
	var nameRole = $('#nameRole').val();
	var orgNameObj = $('#orgNameObj').val();
	var orgId = $('#orgIdObj').val();
	var controlLevel=$('#controlLevelRoleObj').val();
	$.ajax({
		url:"addSysRole.action",
		data:{str:str,
			controlLevel:controlLevel,
			nameRole:nameRole,
			orgNameObj:orgNameObj,
			orgId:orgId},
		dataType:"JSON",
		type:"POST",
		success:function(data){
			if(data=='success'){
				initFrame();
				permissionTree = null;
				searchTable.ajax.reload();
			}
		},
		error:function(e){
			alert("角色..."+e);
		}
	})

	/*$.post('addSysRole.action',{$('#roleForm').serialize(),permissions:str},function(data){
//		$('#closeAddModal').click();
		initFrame();
		permissionTree = null;
		searchTable.ajax.reload();
	});*/
}

function backSearch1(){
	permissionTree = null;
	initFrame();
}

// 展示修改页面
function showEditPage(id){
	/*if(null == permissionTree){
		loadData(showEditPage,id);
	}*/
	$.post('loadAssistData.action',{},function(data){
		permissionTree = $.fn.zTree.init($("#permissionTree"), permissionSetting, data.sysPermissions);
		permissionTree.expandAll(true);
		orgTree = $.fn.zTree.init($("#orgTree"), orgSetting, data.sysOrgs);
		orgTree.expandAll(true);
		
		initFrame();
		$.post('searchRoleById.action',{'id':id},function(data){
			var sysRole = data.sysRole;
			$('#idRole').val(sysRole.id);
			$('#nameRole').val(sysRole.name);//角色名称
			$('#orgNameObj').val(data.orgName);//所属部门
			$('#orgIdObj').val(sysRole.orgId);
			$('#controlLevelRoleObj').val(sysRole.controlLevel);
			$('.upfpanel-title').text("角色修改");
			var sysRolePermission = data.sysRolePermission;
			var treeObj = $.fn.zTree.getZTreeObj("permissionTree");

			var str = data['str'];
			if(str!=null){
				for (var i=0; i < str.length; i++) {
					treeObj.checkNode(treeObj.getNodeByParam("id",str[i]), true);
			     }
			}
			
			$('#updateBtn').show();
//			$('#showRole').click();
			$('#searchContent').hide();
			$('#roleModal').show();
			if(null == $('#roleForm').data('bootstrapValidator')) {
				$('#roleForm').bootstrapValidator(checkValidator);
			}
		});
	});

}

// 权限选择处理
function permissionSelected(){
	$('#permissionNameUl').empty();
	$('#permissions').val('');
	var selectedNodes = permissionTree.getCheckedNodes('checked');
	var ids = '';
	var names = '';
	for(var node in selectedNodes){
		ids += ',' + selectedNodes[node].id;
		names += ',' + selectedNodes[node].name;
		$('#permissionNameUl').append('<li class="list-group-item">\
			    '+selectedNodes[node].name+'\
			    <span class="glyphicon glyphicon-remove move-left" aria-hidden="true" data_id="'
			    +selectedNodes[node].id+'" ></span>\
			  </li>');
	}
	if('' != ids){
		ids = ids.substr(1);
		names = names.substr(1);
	}
	$('#permissions').val(ids);
	$('#permissionCloseModal').click();
	$('#permissionNameUl').find('.glyphicon-remove').click(function(){
		var id = $(this).attr('data_id');
		var ids = '';
		var idArray = $('#permissions').val().split(',');
		for(var per in idArray){
			if(id != idArray[per]){
				ids += ',' + idArray[per];
			}
		}
		if('' != ids){
			ids = ids.substr(1);
		}
		$('#permissions').val(ids);
		$(this).parent().remove();
		return false;
	});
}
// 更新数据
function updateRole(){
	var controlLevel=$('#controlLevelRoleObj').val();
	var updateRoleName = $('#nameRole').val();
	var updateRoleId = $('#idRole').val();
	var updateOrgId = $('#orgIdObj').val();
	
	
	var treeObj2 = $.fn.zTree.getZTreeObj("permissionTree");
	var nodes = treeObj2.getCheckedNodes(true);
	var str2 = '';
	for(var i = 0 ; i < nodes.length; i++){
		str2 += nodes[i].id;
		str2 += ",";	
	}
	$.ajax({
		url:"updateSysRole.action",
		data:{
			controlLevel:controlLevel,
			updateRoleName:updateRoleName,
			updateRoleId:updateRoleId,
			updateOrgId:updateOrgId,
			str2:str2,
		},
		dataType:"JSON",
		type:"POST",
		success:function(data){
			if(data=='success'){
				initFrame();
				permissionTree = null;
				searchTable.ajax.reload();
			}
		},
		error:function(e){
			alert("更新角色时异常："+e);
		}
	})
	
	/*$.post('updateSysRole.action',$('#roleForm').serialize(),function(data){
		$('#closeAddModal').click();
		searchTable.ajax.reload();
	});*/
}

// 删除数据
function del(id,name){
	 if(confirm("是否要删除"+name+"吗？")){
		 $.post('delSysRole.action',{'id':id},function(){
			 searchTable.ajax.reload();
		 });
	 }
}
//返回
function backSearch(){
	initFrame();
	$('#RoleContainer').hide();
}




//角色查看人员
var searchStaffTable;
var dataStaffTableConfig = {
		"ordering": false,// 排序
		"serverSide": true,// 开启服务器模式
		"scrollX": true,// 横向滚动
		ajax: {
			"type": "POST",
			"url":'searchStaff4Page.action',//请求路径
			"contentType": 'application/x-www-form-urlencoded; charset=UTF-8',
			"dataType":'json',
			"data":function(d){// 查询参数
//	        	alert($('#sysRoleName').html());
//	        	d.name = $('#sysRoleName').html();
				d.id = curRoleIdForStaff;
				return d;
			}

		},            
		columns: [// 对应列
		          {"data": "id"},
		          {"data": "code"},
		          {"data": "name"},
		          {"data": "sex"},
		          {"data": "phone"},
		          {"data": "email"},
		          {"data": "mobilPhone"},
		          {"data": "account"},
		          {"data": "status"},
		          {"data": null}
		          ],
		          "columnDefs": [
		                         {// 所有列默认值
		                        	 "targets": "_all",
		                        	 "defaultContent": ''
		                         }]
		,"dom": 'rt<"bottom"ip><"clear">' //生成样式
};
var curRoleIdForStaff;
function roleSearchStaff(id){
	curRoleIdForStaff = id;
//	if(!searchTable){
//		console.log("hello");
//	}else{
//		searchTable.ajax.reload();
//	}
	if(!searchStaffTable){
		searchStaffTable = $("#searchStaffTable").DataTable(dataStaffTableConfig);
	}else{
		searchStaffTable.ajax.reload();
	}
    $('#searchContent').hide();
	$('#RoleContainer').show();
}

function loadDeferScript(){

	/**修改因为高度问题导致分页下移的问题*/

	if(myBrowser() =="IE9"){
		if($(".DTFC_LeftHeadWrapper").length>0&&$(".DTFC_LeftBodyWrapper").length>0){
			var needChangeHeight = $("#searchTable_wrapper .DTFC_ScrollWrapper").height();
			$("#searchTable_wrapper .DTFC_ScrollWrapper").height((needChangeHeight-65)+"px");
		}
		
	}
}

$(document).on('click','#searchTable_paginate li.paginate_button a',function(){

	setTimeout("loadDeferScript()", 1000);
});

$(document).on('click','#searchStaffTable_paginate li.paginate_button a',function(){

	setTimeout("loadDeferScript()", 1000);
});



